#
# mlbtv-xbmc-plugin
# $Id$
# Copyright 2009 Brian Dols <dols@68k.org>, All Rights Reserved
#
#          Licensed under the Apache License, Version 2.0 (the "License");
#          you may not use this file except in compliance with the License.
#          You may obtain a copy of the License at
#
#             http://www.apache.org/licenses/LICENSE-2.0
#
#           Unless required by applicable law or agreed to in writing,
#           software distributed under the License is distributed on an
#           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#           KIND, either express or implied.  See the License for the
#           specific language governing permissions and limitations
#           under the License.    
#
#
from MLBviewer import MLBSchedule
from MLBviewer import GameStream
from MLBviewer import MLBConfig
from MLBviewer import MLBJsonError
from MLBviewer import AUTHDIR, AUTHFILE
from MLBviewer import TEAMCODES
from mlbtv import check_tuner,check_and_install_config,kill_tuner

import xbmcgui, xbmc, os, time, datetime
import subprocess, signal


__language__ = xbmc.Language( os.getcwd() ).getLocalizedString
__path__ = os.getcwd() + '\\'
__team__ = __language__(32015)

DEFAULT_V_ARGS = '-cache 8192 -softvol -fixed-vo -autosync 30 -nolirc'
DEFAULT_A_PLAYER = 'mplayer -cache 64 -really-quiet'
DEFAULT_SPEED = '800'
STREAM_SPEEDS = ( '164', '400', '600', '800', '1200', '1800', '2200', '3000' )
TUNER_LIST = ('001', '002', '003', '004')

statusline = {
    "I" : "Status: In Progress",
    "W" : "Status: Not Yet Available",
    "F" : "Status: Final",
    "CG": "Status: Final (Condensed Game Available)",
    "P" : "Status: Not Yet Available",
    "S" : "Status: Suspended",
    "D" : "Status: Delayed",
    "IP": "Status: Pregame",
    "PO": "Status: Postponed",
    "GO": "Status: Game Over - stream not yet available",
    "NB": "Status: National Blackout",
    "LB": "Status: Local Blackout"}




class DialogProgress(xbmcgui.DialogProgress):
    def __init__(self):
        self.create(' ')

class BlueButton:
    def __init__(self,x1,y1,x2,y2,string):
        self.x1 = x1
        self.x2 = x2
        self.y1 = y1
        self.y2 = y2
        self.s = string
    def get(self):
        return xbmcgui.ControlButton(self.x1,self.y1,self.x2,self.y2,self.s,focusedColor="0xFF00FFFF")

class MLBWindow(xbmcgui.Window):
    def __init__(self):

        self.myconfdir = os.path.join(os.environ['HOME'],AUTHDIR)
        self.myconf =  os.path.join(self.myconfdir,AUTHFILE)
        self.mydefaults = {'speed': DEFAULT_SPEED,
                  'video_args': DEFAULT_V_ARGS,
                  'audio_player': DEFAULT_A_PLAYER,
                  'audio_follow': [],
                  'video_follow': [],
                  'blackout': [],
                  'favorite': [],
                  'use_color': 0,
                  'favorite_color': 'cyan',
                  'bg_color': 'xterm',
                  'show_player_command': 0,
                  'debug': 0,
                  'x_display': '',
                  'top_plays_player': '',
                  'time_offset': None,
                  'max_bps': 800000,
                  'live_from_start': 0,
                  'use_nexdef': 1,
                  'strict_stream': 1,
                  'coverage' : 'home',
                  'show_inning_frames': 1,
                  'flash_browser': None }
        # auto install default config
        result = check_and_install_config()
        self.mycfg = result['data']
        self.now = datetime.datetime.now()
        self.dif = datetime.timedelta(1)
        if self.now.hour < 9:
            self.now = self.now - self.dif


        self.startdate = (self.now.year, self.now.month, self.now.day)

        self.dateDisplay = xbmcgui.ControlLabel(50,600,200,40,'')
        self.addControl(self.dateDisplay)

        self.username = ""
        self.password = ""
        self.addControl(xbmcgui.ControlImage(0,0,720,480,__path__ + 'resources\\images\\background.tbn'))
        
        self.gameControls = {}
        self.button0 = BlueButton(30,125,250,40,__language__(32001)).get()
        self.addControl(self.button0)
        self.button0.setEnabled(False)
        self.button1 = BlueButton(30,175,250,40,"Today's Games").get()
        self.addControl(self.button1)
        self.button2 = BlueButton(30,225,250,40,__language__(32003)).get()
        self.addControl(self.button2)
        self.button3 = BlueButton(30,275,250,40,"Tuners").get()
        self.addControl(self.button3)
        #self.button3.setEnabled(False)
        self.button4 = BlueButton(30,325,250,40,__language__(32005)).get()
        self.addControl(self.button4)
        self.button4.setEnabled(False)
        self.button5 = BlueButton(30,375,250,40,__language__(32006)).get()
        self.addControl(self.button5)
        self.button5.setEnabled(False)


        self.button0.controlUp(self.button5)
        self.button0.controlDown(self.button1)
        self.button1.controlUp(self.button0)
        self.button1.controlDown(self.button2)
        self.button2.controlUp(self.button1)
        self.button2.controlDown(self.button3)
        self.button3.controlUp(self.button2)
        self.button3.controlDown(self.button4)
        self.button4.controlUp(self.button3)
        self.button4.controlDown(self.button5)
        self.button5.controlUp(self.button4)
        self.button5.controlDown(self.button0)

        self.setFocus(self.button1)
        print "how you doing"

    def onControl(self, control):
        cfg = self.mycfg.data
        print control
        if control in self.gameControls.values():
            print "how you doing"
            for game in self.gameControls.keys():
                if self.gameControls[game] == control:
                    print "this is the game ", game
                    for listing in self.available:
                        if listing[5] == game:
                            print "this is the entry ", listing
                            gameListing = GameListing(listing=listing,config=self.mycfg,mysched=self.mysched)
                            gameListing.doModal()
                            vid=gameListing.getPlaying()
                            del gameListing
                            print "i am done"
                            if vid != None:
                                print "is playing? " , vid.isPlaying()
        if control == self.button0:
            kb0 = xbmc.Keyboard(__language__(32010),__language__(32011))
            kb0.setHiddenInput(False)
            kb0.doModal()
            if kb0.isConfirmed():
                self.username = kb0.getText()
                kb1 = xbmc.Keyboard(__language__(32012),__language__(32013))
                kb1.setHiddenInput(True)
                kb1.doModal()
                if kb1.isConfirmed():
                    self.password = kb1.getText()
        if control == self.button2:
            kb0 = xbmc.Keyboard("%d" % self.now.month, "Enter month")
            kb0.setHiddenInput(False)
            kb0.doModal()
            if kb0.isConfirmed():
                month = kb0.getText()
                kb1 = xbmc.Keyboard("%d" % self.now.day, "Enter day for the month")
                kb1.setHiddenInput(False)
                kb1.doModal()
                if kb1.isConfirmed():
                    day = kb1.getText()
                    try:
                        dateDisp = datetime.date(self.now.year, int(month), int(day))
                        self.startdate = (self.now.year, int(month), int(day))
                        self.dateDisplay.setLabel("Date: " + dateDisp.strftime("%Y-%m-%d"))
                    except Exception, e:
                        print "date exception", e
                        pass
        if control == self.button1 or control == self.button2:
            if control != self.button2:
                self.now = datetime.datetime.now()
                self.dif = datetime.timedelta(1)
                if self.now.hour < 9:
                    self.now = self.now - self.dif
                dateDisp = datetime.date(self.now.year, self.now.month, self.now.day)
                self.startdate = (self.now.year, self.now.month, self.now.day)
                self.dateDisplay.setLabel("Date: " + time.strftime("%Y-%m-%d",time.localtime(time.time())))
            dp0 = DialogProgress()
            dp0.create(__language__(32017))
            dp0.update(0,__language__(32018))
            self.mysched = MLBSchedule(ymd_tuple=self.startdate,time_shift=cfg['time_offset'])
            today_year = self.mysched.year
            today_month = self.mysched.month
            today_day = self.mysched.day
            if dp0.iscanceled(): return
            try:
                self.available = self.mysched.getListings(cfg['speed'],cfg['blackout'],cfg['audio_follow'])
            except (KeyError, MLBJsonError), detail:
                print "exception"
                #raise Exception,detail
                if cfg['debug']:
                    raise Exception, detail
                available = []
                status_str = "There was a parser problem with the listings page"
                print status_str
                dp0.update(100,status_str) # TODO

            
            dp0.update(50,"parsing")
            use_xml = self.mysched.use_xml
            print self.available[0]
            offset=0
            for i in self.gameControls.values():
                self.removeControl(i)
            self.gameControls.clear()
            lastControl = None
            for game in self.available:
                home = game[0]['home']
                away = game[0]['away']
                s = game[1].strftime('%l:%M %p') + ': ' +\
                    ' '.join(TEAMCODES[away][1:]).strip() + ' at ' +\
                    ' '.join(TEAMCODES[home][1:]).strip()
                if game[4] in ('P', 'W'):
                    s+= ' (Not Yet Available)'
                if game[4] == 'IP':
                    s+= ' (Pre-Game)'
                if game[4] == 'S':
                    s+= ' (Suspended)'
                if game[4] == 'D':
                    s+= ' (Delayed)'
                if game[4] == "NB":
                    s+= ' (National Blackout)'
                if game[4] == "LB":
                    s+= ' (Local Blackout)'
                if game[4] == 'PO':
                    s+= ' (Postponed)'
                if game[4] in ('F', 'CG'):
                    s+= ' (Archived)'
                elif use_xml and game[6] == 'media_archive':
                    s+= ' (Archived)'
                control = BlueButton(310,135+offset,800,30,s).get()
                self.addControl(control)
                if lastControl!=None:
                    lastControl.controlDown(control)
                    control.controlUp(lastControl)
                else:
                    self.button1.controlRight(control)
                    self.button2.controlRight(control)
                    self.button3.controlRight(control)
                    self.button4.controlRight(control)
                    self.button5.controlRight(control)
                if game[4] in ('P', 'W', 'NB', 'LB', 'PO'):
                    control.setEnabled(False)
                lastControl = control
                self.gameControls[game[5]]=control
                offset+=35

            for i in self.gameControls.values():
                i.controlLeft(self.button1)

            if dp0.iscanceled(): return
            dp0.update(100,__language__(32022))
            dp0.close()
        if control == self.button3:
            print self.mycfg.data
            try:
                tuners = Tuners(config=self.mycfg.data)
                tuners.doModal()
            except Exception, e:
                print e
    def onAction(self, action):
        if action == 9 or action == 10: # ACTION_PREVIOUS_MENU:
            self.close()


class Tuners(xbmcgui.Window):
    def __init__(self,config=None):
        self.cfg = config
        self.addControl(xbmcgui.ControlImage(0,0,720,480,__path__ + 'resources\\images\\background.tbn'))
        i = 0  
        self.playButtons = {}
        self.stopButtons = {}
        for tuner in TUNER_LIST:
            tl = xbmcgui.ControlLabel(100,125+i*50,200,40,"Tuner %s" % tuner)
            self.addControl(tl)
            dump_loc = self.cfg['video_cache']
            if dump_loc == None:
                dump_loc = os.getcwd()
            if check_tuner(dump_loc,tuner):
                play = BlueButton(320,125+i*50,60,40,"Play").get()
                self.addControl(play)
                self.playButtons[tuner] = play
                stop = BlueButton(380,125+i*50,60,40,"Stop").get()
                self.addControl(stop)
                play.controlRight(stop)
                stop.controlLeft(play)
                self.stopButtons[tuner] = stop
            else:
                topen = xbmcgui.ControlLabel(320,125+i*50,200,40,"Open")
                self.addControl(topen)
            i+=1
            
    def onControl(self, control):
        if control in self.playButtons.values():
            listitem = xbmcgui.ListItem("MLB Game")
            listitem.setInfo('video', {'Title': "MLB Game", 'Genre': "Sports"})
            for i in self.playButtons.keys():
                if control==self.playButtons[i]:
                    dump_loc = self.cfg['video_cache']
                    if dump_loc == None:
                        dump_loc = os.getcwd()
                    vid=xbmc.Player()
                    vid.play("%s/%smlbtv.flv" % (dump_loc,i) ,listitem)
                    break
        if control in self.stopButtons.values():
            for i in self.stopButtons.keys():
                if control==self.stopButtons[i]:
                    dump_loc = self.cfg['video_cache']
                    if dump_loc == None:
                        dump_loc = os.getcwd()
                    ret = kill_tuner(dump_loc,i)
                    print "killed ", ret
    def onAction(self, action):
        if action == 9 or action == 10: # ACTION_PREVIOUS_MENU:
            self.close()
class GameListing(xbmcgui.Window):
    def __init__(self,listing=None,config=None,mysched=None):
        self.cfg = config
        print "hi ", listing
        self.mysched=mysched
        self.addControl(xbmcgui.ControlImage(0,0,720,480,__path__ + 'resources\\images\\background.tbn'))
        self.awayTeamDisplay = xbmcgui.ControlLabel(200,125,400,40,'')
        self.homeTeamDisplay = xbmcgui.ControlLabel(600,125,400,40,'')
        self.atDisplay = xbmcgui.ControlLabel(550,125,50,40,'')
        self.addControl(self.homeTeamDisplay)
        self.addControl(self.awayTeamDisplay)
        self.addControl(self.atDisplay)
        self.atDisplay.setLabel("at")
        home = listing[0]['home']
        away = listing[0]['away']
        awayDisplay = ' '.join(TEAMCODES[away][1:]).strip() 
        homeDisplay = ' '.join(TEAMCODES[home][1:]).strip()
        self.gameLabel = "%s at %s" % (awayDisplay, homeDisplay)
        self.homeTeamDisplay.setLabel(homeDisplay)
        self.awayTeamDisplay.setLabel(awayDisplay)
        print len(listing[2])
        self.awayVideoDisplay = self.awayVideoStream = None
        self.homeVideoDisplay = self.homeVideoStream = None
        self.awayRadioDisplay = self.awayRadioStream = None
        self.homeRadioDisplay = self.homeRadioStream = None
        self.videoDisplay = xbmcgui.ControlLabel(100,180,100,40,'Video')
        self.radioDisplay = xbmcgui.ControlLabel(100,430,100,40,'Radio')
        self.addControl(self.videoDisplay)
        self.addControl(self.radioDisplay)
        self.start_time = 0
        self.vid = None
        if len(listing[2]) > 0:
            print listing[2][0][0]
            if listing[2][0][1] == TEAMCODES[away][0]:
                self.awayVideoDisplay = BlueButton(220,175,150,40,listing[2][0][0]).get()
                self.addControl(self.awayVideoDisplay)
                self.setFocus(self.awayVideoDisplay)
                self.awayVideoStream = listing[2][0]
            elif listing[2][0][1] == TEAMCODES[home][0]:
                self.homeVideoDisplay = BlueButton(620,175,150,40,listing[2][0][0]).get()
                self.addControl(self.homeVideoDisplay)
                self.setFocus(self.homeVideoDisplay)
                self.homeVideoStream = listing[2][0]
            else:
                self.awayVideoDisplay = BlueButton(220,175,150,40,listing[2][0][0]).get()
                self.addControl(self.awayVideoDisplay)
                self.setFocus(self.awayVideoDisplay)
                self.awayVideoStream = listing[2][0]
            if len(listing[2]) > 1:
                print listing[2][1][0]
                if listing[2][1][1] == TEAMCODES[away][0]:
                    self.awayVideoDisplay = BlueButton(220,175,150,40,listing[2][1][0]).get()
                    self.addControl(self.awayVideoDisplay)
                    self.awayVideoStream = listing[2][1]
                elif listing[2][1][1] == TEAMCODES[home][0]:
                    self.homeVideoDisplay = BlueButton(620,175,150,40,listing[2][1][0]).get()
                    self.addControl(self.homeVideoDisplay)
                    self.homeVideoStream = listing[2][1]
                else:
                    self.homeVideoDisplay = BlueButton(620,175,150,40,listing[2][1][0]).get()
                    self.addControl(self.awayVideoDisplay)
                    self.homeVideoStream = listing[2][1]
        self.topPlays = None
        self.topPlaysDisplay = None
        self.condensedDisplay = None
        if len(listing) >= 5 and listing[5] != None and listing[5] != "":
            if listing[4] == "CG":
                print "listing ", listing[5]
                self.condensedStream = self.mysched.getCondensedVideo(listing[5])
                print "condensed ", self.condensedStream
                self.condensedDisplay = BlueButton(470,225,250,40,"Condensed review").get()
                self.addControl(self.condensedDisplay)
            self.topPlays = self.mysched.getTopPlays(listing[5])
            if self.topPlays != None and len(self.topPlays) > 0:
                print "top plays ", repr(self.topPlays)
                self.topPlaysDisplay = BlueButton(220,225,250,40,"Top plays").get()
                self.addControl(self.topPlaysDisplay)


        if len(listing[3]) > 0:
            self.inningsTopDisplay = {}
            self.inningsBottomDisplay = {}
            try:
                self.innings={}
                this_event = listing[2][0][3]
                print "pre innings parse ", this_event
                self.myinnings = self.mysched.parse_innings_xml(this_event)
                for inning in range(len(self.myinnings)):
                    # top half innings will be 1 - 10, 10 being extra innings
                    # bottom half innings will be top half plus 10
                    if self.myinnings[inning][1] == 'false':
                        self.innings[int(self.myinnings[inning][0]) + 10] = self.myinnings[inning][2]
                    else:
                        self.innings[int(self.myinnings[inning][0])] = self.myinnings[inning][2]
                print repr(self.innings)
                print repr(self.myinnings)
                j=0 
                for i in "1","2","3","4","5","6","7","8","9","E":
                    disp = xbmcgui.ControlLabel(220+j*40,305,70,40,i)
                    self.addControl(disp)
                    j+=1
                self.awayShortDisplay = xbmcgui.ControlLabel(140,335,70,40,listing[0]['away'].upper())
                self.homeShortDisplay = xbmcgui.ControlLabel(140,385,70,40,listing[0]['home'].upper())
                self.addControl(self.awayShortDisplay)
                self.addControl(self.homeShortDisplay)
                for i in range(1,21):
                    label = 'X'
                    if not self.innings.has_key(i):
                        label = '-'
                    if i > 10:
                        if i == 19:
                            if self.innings.has_key(9):
                                label = '?' #hides home victory spoiler
                            if self.innings.has_key(20):
                                label = 'X'
                        disp = xbmcgui.ControlRadioButton(170+(i-10)*40,375,20,40,label,focusedColor="0xFF00FFFF")
                        self.addControl(disp)
                        if label != 'X':
                            disp.setEnabled(False)
                        self.inningsBottomDisplay[i]=disp
                        
                        self.inningsBottomDisplay[i].controlUp(self.inningsTopDisplay[i-10])
                        self.inningsTopDisplay[i-10].controlDown(self.inningsBottomDisplay[i])
                        if i > 11:
                            self.inningsBottomDisplay[i].controlLeft(self.inningsBottomDisplay[i-1])
                            self.inningsBottomDisplay[i-1].controlRight(self.inningsBottomDisplay[i])
                    else:
                        disp = xbmcgui.ControlRadioButton(170+i*40,325,20,40,label,focusedColor="0xFF00FFFF")
                        self.addControl(disp)
                        if label == '-':
                            disp.setEnabled(False)
                        self.inningsTopDisplay[i]=disp
                        if self.topPlaysDisplay != None:
                            self.inningsTopDisplay[i].controlUp(self.topPlaysDisplay)
                        elif self.condensedDisplay != None:
                            self.inningsTopDisplay[i].controlUp(self.condensedDisplay)
                        if i > 1:
                            self.inningsTopDisplay[i].controlLeft(self.inningsTopDisplay[i-1])
                            self.inningsTopDisplay[i-1].controlRight(self.inningsTopDisplay[i])
            except Exception, e:
                print e
                pass



        if len(listing[3]) > 0:
            print listing[3][0][0]

            if listing[3][0][1] == TEAMCODES[away][0]:
                self.awayRadioDisplay = BlueButton(220,425,150,40,listing[3][0][0]).get()
                self.addControl(self.awayRadioDisplay)
                self.awayRadioStream = listing[3][0]
            elif listing[3][0][1] == TEAMCODES[home][0]:
                self.homeRadioDisplay = BlueButton(620,425,150,40,listing[3][0][0]).get()
                self.addControl(self.homeRadioDisplay)
                self.homeRadioStream = listing[3][0]
            else:
                self.awayRadioDisplay = BlueButton(220,425,150,40,listing[3][0][0]).get()
                self.addControl(self.awayRadioDisplay)
                self.awayRadioStream = listing[3][0]

            if len(listing[3]) > 1:
                print listing[3][1][0]

                if listing[3][1][1] == TEAMCODES[away][0]:
                    self.awayRadioDisplay = BlueButton(220,425,150,40,listing[3][1][0]).get()
                    self.addControl(self.awayRadioDisplay)
                    self.awayRadioStream = listing[3][1]
                elif listing[3][1][1] == TEAMCODES[home][0]:
                    self.homeRadioDisplay = BlueButton(620,425,150,40,listing[3][1][0]).get()
                    self.addControl(self.homeRadioDisplay)
                    self.homeRadioStream = listing[3][1]
                else:
                    self.homeRadioDisplay = BlueButton(620,425,150,40,listing[3][1][0]).get()
                    self.addControl(self.awayRadioDisplay)
                    self.homeRadioStream = listing[3][1]
        if self.topPlaysDisplay != None:
            if self.awayVideoDisplay != None:
                print "top up"
                self.topPlaysDisplay.controlUp(self.awayVideoDisplay)
                self.awayVideoDisplay.controlDown(self.topPlaysDisplay)
            elif self.homeVideoDisplay != None:
                print "top up2"
                self.topPlaysDisplay.controlUp(self.homeVideoDisplay)
            if self.homeVideoDisplay != None:
                self.homeVideoDisplay.controlDown(self.topPlaysDisplay)
            if self.condensedDisplay != None:
                self.topPlaysDisplay.controlRight(self.condensedDisplay)
                self.condensedDisplay.controlLeft(self.topPlaysDisplay)

        if self.awayVideoDisplay != None and self.homeVideoDisplay != None:
            print "aiieee"
            self.awayVideoDisplay.controlRight(self.homeVideoDisplay)
            self.homeVideoDisplay.controlLeft(self.awayVideoDisplay)
        if self.awayRadioDisplay != None and self.homeRadioDisplay != None:
            print "iieee"
            self.awayRadioDisplay.controlRight(self.homeRadioDisplay)
            self.awayRadioDisplay.controlLeft(self.homeRadioDisplay)
            self.homeRadioDisplay.controlLeft(self.awayRadioDisplay)
            self.homeRadioDisplay.controlRight(self.awayRadioDisplay)
        if len(self.inningsTopDisplay.values()) > 0:
            for i in self.topPlaysDisplay, self.condensedDisplay:
                if i != None:
                    i.controlDown(self.inningsTopDisplay[1])
        else:
            for i in self.topPlaysDisplay, self.condensedDisplay:
                if i != None:
                    if self.awayRadioDisplay != None:
                        i.controlDown(self.awayRadioDisplay)
                    elif self.homeRadioDisplay != None:
                        i.controlDown(self.homeRadioDisplay)
                        
        if len(self.inningsBottomDisplay.values()) == 0:
            for i in self.homeRadioDisplay, self.awayRadioDisplay :
                if i != None:
                    if self.topPlaysDisplay != None:
                        i.controlUp(self.topPlaysDisplay)
                        self.topPlaysDisplay.controlDown(i)
                    elif self.condensedDisplay != None:
                        i.controlUp(self.condensedDisplay)
                        self.condensedDisplay.controlDown(i)
                    elif self.awayVideoDisplay != None:
                        i.controlUp(self.awayVideoDisplay)
                        self.awayVideoDisplay.controlDown(i)
                        if self.homeVideoDisplay != None:
                            self.homeVideoDisplay.controlDown(i)
        first = False
        for i in self.inningsBottomDisplay.values():
        
            if self.awayRadioDisplay != None:
                i.controlDown(self.awayRadioDisplay)
                if not first:
                    self.awayRadioDisplay.controlUp(i)
            elif self.homeRadioDisplay != None:
                i.controlDown(self.homeRadioDisplay)
            if self.homeRadioDisplay != None:
                if not first:
                    self.homeRadioDisplay.controlUp(i)
            first = True

    def onControl(self, control):
        cfg = self.cfg.data
        if control == self.awayRadioDisplay:
            g = GameStream(self.awayRadioStream, cfg['user'], cfg['pass'],
                                   cfg['debug'], streamtype='audio',
                                   use_soap=True, use_nexdef=False,
                                   coverage=self.awayRadioStream[1],log_file=cfg['log_file'])
            u = g.soapurl()
            print u
            print g.call_letters
        elif control == self.homeRadioDisplay:
            g = GameStream(self.homeRadioStream, cfg['user'], cfg['pass'],
                                   cfg['debug'], streamtype='audio',
                                   use_soap=True, use_nexdef=False,
                                   coverage=self.homeRadioStream[1],log_file=cfg['log_file'])
            u = g.soapurl()
            print u
            print g.call_letters
        elif control == 1: # if streaming in XBMC magically worked all of the sudden
        #elif control == self.awayVideoDisplay or control == self.homeVideoDisplay:
            if control == self.awayVideoDisplay:
                stream = self.awayVideoStream
            elif control == self.homeVideoDisplay:
                stream = self.homeVideoStream
            g = GameStream(stream, cfg['user'], cfg['pass'], cfg['debug'], streamtype='video',
                               use_soap=True, use_nexdef=cfg['use_nexdef'], speed=cfg['speed'],
                               coverage=stream[1], max_bps=cfg['max_bps'],log_file=cfg['log_file'])
            u = g.soapurl()
            self.vid = xbmc.Player()
            listitem = xbmcgui.ListItem(self.gameLabel)
            listitem.setInfo('video', {'Title': self.gameLabel, 'Genre': "Sports"})
            print u
            self.vid.play(str(u),listitem)
        elif control == self.topPlaysDisplay:
            topPlaysListing = TopPlaysListing(topPlays=self.topPlays)
            topPlaysListing.doModal()
            del topPlaysListing
        elif control == self.condensedDisplay:
            self.vid = xbmc.Player()
            listitem = xbmcgui.ListItem(self.gameLabel)
            listitem.setInfo('video', {'Title': self.gameLabel, 'Genre': "Sports"})
            print "playing condensed ", self.condensedStream
            self.vid.play(self.condensedStream, listitem)
        elif control in self.inningsTopDisplay.values() or control in self.inningsBottomDisplay.values():
            for i in self.inningsTopDisplay, self.inningsBottomDisplay:
                for j in i.keys():
                    if i[j].isSelected() and i[j] != control:
                        i[j].setSelected(False)
                        i[j].setLabel("X",textColor="0xFFFFFFFF",focusedColor="0xFF00FFFF")
                    if i[j] == control:
                        if self.innings.has_key(j):
                            if i[j].isSelected():
                                i[j].setLabel("X",textColor="0xFFFF0000",focusedColor="0xFFFF0000")
                            else:
                                i[j].setLabel("X",textColor="0xFFFFFFFF",focusedColor="0xFF00FFFF")
                            print "setting time to ", self.innings[j]
                            self.start_time = self.innings[j]

        elif control == self.awayVideoDisplay or control == self.homeVideoDisplay:
            if control == self.awayVideoDisplay:
                stream = self.awayVideoStream
            elif control == self.homeVideoDisplay:
                stream = self.homeVideoStream
            dp0 = DialogProgress()
            dp0.create("Opening video stream")
            if self.start_time == 0:
                g = GameStream(stream, cfg['user'], cfg['pass'],
                                        cfg['debug'], streamtype='video',
                                        use_soap=True, use_nexdef=cfg['use_nexdef'],
                                        speed=cfg['speed'],
                                        coverage=stream[1],
                                        max_bps=cfg['max_bps'],start_time=None,log_file=cfg['log_file'])
            else:
                print "using start time ", self.start_time
                g = GameStream(stream, cfg['user'], cfg['pass'],
                                        cfg['debug'], streamtype='video',
                                        use_soap=True, use_nexdef=cfg['use_nexdef'],
                                        speed=cfg['speed'],
                                        coverage=stream[1],
                                        max_bps=cfg['max_bps'],start_time=self.start_time,log_file=cfg['log_file'])

            dp0.update(33,"Authorizing")
            try:
                u = g.soapurl()
                print u
                dp0.update(66,"Buffering")
                if cfg['use_nexdef'] == 0:
                    dump_loc = cfg['video_cache']
                    if dump_loc == None:
                        dump_loc = os.getcwd()
                    for tuner in TUNER_LIST:
                        if not check_tuner(dump_loc,tuner):
                            break
                    cmd_str = u
                    cmd_str = cmd_str.replace('-o -',"-o %s/%smlbtv.flv" % (dump_loc,tuner))
                    class MLBFLVPlayer(xbmc.Player):
                        def __init__ (self):
                            pid = os.fork()
                            if pid == 0:
                                os.setsid()
                                os.chdir("/")
                                os.umask(0)
                                sys.stdin.close()
                                sys.stdout.close()
                                sys.stderr.close()
                                child_pid = os.fork()
                                if child_pid == 0:
                                    print cmd_str
                                    cmd = cmd_str.split(' ')
                                    os.execv("/usr/local/bin/rtmpdump", cmd)
                                else:
                                    pid_file = open("%s/%smlbtv.pid" % (dump_loc,tuner),'w')
                                    pid_file.write("%s\n"%child_pid)
                                    pid_file.close()
                                    os._exit(0)
                    self.vid = MLBFLVPlayer()

                else:
                    mplayer_path = cfg['mplayer_path']
                    if mplayer_path == None:
                        mplayer_path = 'mplayer'
                    cmd_str = cfg['video_args']
                    dump_loc = cfg['video_cache']
                    if dump_loc == None:
                        dump_loc = os.getcwd()
                    for tuner in TUNER_LIST:
                        if not check_tuner(dump_loc,tuner):
                            break
                    cmd_str += " -dumpstream -dumpfile %s/%smlbtv.flv " % (dump_loc,tuner)
                    if cmd_str.find('%s')>=0:
                        cmd_str = cmd_str.replace('%s', u )
                    else:
                        cmd_str = cmd_str + ' ' + u + ' '
                    print "CWD ", os.getcwd()
                    print "cached ", cfg['video_cache']
                    class MLBNexDefPlayer(xbmc.Player):
                        def __init__ (self):
                            #self.play_process=subprocess.Popen(cmd_str,shell=True, preexec_fn=os.setsid)
                            pid = os.fork()
                            if pid == 0:
                                os.setsid()
                                os.chdir("/")
                                os.umask(0)
                                sys.stdin.close()
                                sys.stdout.close()
                                sys.stderr.close()
                                child_pid = os.fork()
                                if child_pid == 0:
                                    print cmd_str
                                    cmd = cmd_str.split(' ')
                                    cmd.reverse()
                                    cmd.append(mplayer_path)
                                    cmd.reverse()
                                    os.execv(mplayer_path, cmd)
                                else:
                                    pid_file = open("%s/%smlbtv.pid" % (dump_loc,tuner),'w')
                                    pid_file.write("%s\n"%child_pid)
                                    pid_file.close()
                                    os._exit(0)
                    self.vid = MLBNexDefPlayer()
                i=0
                while i<30:
                    dp0.update(70+i,"Buffering")
                    i+=1
                    time.sleep(2)
                    if dp0.iscanceled(): return
                dp0.close()
                #xbmc_player = xbmc.Player(xbmc.PLAYER_CORE_MPLAYER)
                listitem = xbmcgui.ListItem(self.gameLabel)
                listitem.setInfo('video', {'Title': self.gameLabel, 'Genre': "Sports"})
                self.vid.play("%s/%smlbtv.flv" % (dump_loc,tuner) ,listitem)
                #print "still here"
                #dp1 = DialogPrgress()
                #dp1.create("Waiting for streaming to end")
                #dp1.update(0,"Waiting")
                #vid.getProcess().wait()
                #dp1.update(100,"Done")
                #time.sleep(1)
                #dp1.close()
                #print "done waiting"
            except Exception, e:
                print "Error exception: " , e
                dp0.update(100,str(e).strip())
                time.sleep(2)
                dp0.update(100,"Possible blackout")
                time.sleep(2)
                dp0.close()

        
    def onAction(self, action):
        if action == 9 or action == 10: # ACTION_PREVIOUS_MENU:
            self.close()
    def getPlaying(self):
        return self.vid

class TopPlaysListing(xbmcgui.Window):
    def __init__(self,topPlays=None):
        self.addControl(xbmcgui.ControlImage(0,0,720,480,__path__ + 'resources\\images\\background.tbn'))
        self.topPlays = topPlays
        print repr(topPlays)
        self.playList = {}
        self.buttons = []
        j=0
        if len(self.topPlays) > 0:
            label = self.topPlays[0][0] + " highlights"
        else:
            label = "No highlights"
        self.display = xbmcgui.ControlLabel(100,130,600,40,label)
        self.addControl(self.display)
        first = False
        for i in self.topPlays:
            play = BlueButton(220,175+j*40,600,40,i[1]).get()
            self.buttons.append(play)
            self.addControl(play)
            if not first:
                self.setFocus(play)
                first = True
            self.playList[i[1]] = i[2]
            j+=1
        if len(self.buttons) > 0:
            #self.setFocus(self.buttons[0])
            for i in range(0,len(self.buttons)-1):
                self.buttons[i].controlDown(self.buttons[i+1])
                self.buttons[i+1].controlUp(self.buttons[i])
                
    def onControl(self, control):
        if control in self.buttons:
            print control.getLabel()
            if self.playList.has_key(control.getLabel()):
                url = self.playList[control.getLabel()]
                vid = xbmc.Player()
                listitem = xbmcgui.ListItem(control.getLabel())
                listitem.setInfo('video', {'Title': control.getLabel(), 'Genre': "Sports"})
                vid.play(str(url),listitem)
    def onAction(self, action):
        if action == 9 or action == 10: # ACTION_PREVIOUS_MENU:
            self.close()
        
print "MLB banner"
window = MLBWindow()
window.doModal()
del window
